package com.nartosoft.tubuloader;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author mf
 * 
 * Writes uploaded files + URL + timestamp to HTML file for further reference.
 */
public class HtmlFileWriter extends EventListenerAdapter {

	private final String fileName;

	private final SimpleDateFormat dateFormatter;

	public HtmlFileWriter(String fileName) throws IOException {
		this.fileName = fileName;
		dateFormatter = new SimpleDateFormat("yyyy-MM-dd, HH:mm");
		File f = new File(fileName);
		if (!f.exists()) {
			f.createNewFile();
			FileWriter fileWriter = new FileWriter(f, true);
			fileWriter
					.write("<html>\n<head>\n<title>my 666kb.com uploads</title>\n</head>\n<body>\n</body>");
			fileWriter.close();
		}
	}

	public void onUpload(String fileName, String url) {
		writeToHtmlFile(fileName, url);
	}

	private void writeToHtmlFile(String uploadedFileName, String url) {
		String htmlText = Utils.readFile(fileName);
		if (htmlText == null) {
			return;
		}
		int bodyStartIndex = htmlText.indexOf("<body>");
		if (bodyStartIndex < 0) {
			return;
		}
		String newEntry = getImgElement(uploadedFileName, url) + "<br/>\n"
				+ getUrlElement(url) + " (" + getDateString() + ")<p/>";
		String newHtmlText = htmlText.substring(0, bodyStartIndex+6)  + "\n" + newEntry + 
		htmlText.substring(bodyStartIndex+6, htmlText.length());

		try {
			Writer fw = new FileWriter(fileName);
			fw.write(newHtmlText);
			fw.close();
		}
		catch (IOException exc) {
			exc.printStackTrace();
		}
	}

	private String getImgElement(String fileName, String url) {
		return "<img alt=\"" + fileName + "\" src=\""+ url
				+ "\"/>";
	}

	private String getUrlElement(String url) {
		return "<a href=\"" + url + "\">" + url + "</a>";
	}

	private String getDateString() {
		return dateFormatter.format(new Date());
	}
}
